package org.bambrikii.kbManager.kb2.managers.query4.impl.builders.hql.q;

import java.util.Iterator;
import java.util.Set;

import org.bambrikii.kbManager.kb2.managers.query4.And;
import org.bambrikii.kbManager.kb2.managers.query4.ConditionSource;
import org.bambrikii.kbManager.kb2.managers.query4.ConditionType;
import org.bambrikii.kbManager.kb2.managers.query4.ICondition;
import org.bambrikii.kbManager.kb2.managers.query4.In;
import org.bambrikii.kbManager.kb2.managers.query4.Like;
import org.bambrikii.kbManager.kb2.managers.query4.Or;
import org.bambrikii.kbManager.kb2.managers.query4.impl.builders.QueryBuilderBase;
import org.bambrikii.kbManager.kb2.managers.query4.impl.builders.hql.AndImpl;
import org.bambrikii.kbManager.kb2.managers.query4.impl.builders.hql.InImpl;
import org.bambrikii.kbManager.kb2.managers.query4.impl.builders.hql.LikeImpl;
import org.bambrikii.kbManager.kb2.managers.query4.impl.builders.hql.OrImpl;

public class HQLQueryBuilder extends QueryBuilderBase<HQLCriteria> {

	public String buildQueryString() {
		HQLCriteria crit = getWhere().buildCriteria();
		StringBuilder sb = new StringBuilder();
		Set<ConditionSource> fromList = crit.getFrom();
		Iterator<ConditionSource> fromIt = fromList.iterator();
		// ConditionSource from0 = null;
		if (fromIt.hasNext()) {
			ConditionSource from = fromIt.next();
			// from0 = from;
			sb.append(" join ").append(from.getName()).append(" as ")
					.append(from.getAlias());
			while (fromIt.hasNext()) {
				sb.append("\n");
				from = fromIt.next();
				sb.append(" join ").append(from.getName()).append(" as ")
						.append(from.getAlias());
			}
		}
		String where = crit.getCondition();
		return " select src" /* + from0.getAlias() */
				+ " \nfrom ArtefactAsText src \n" + sb.toString() + " \nwhere"
				+ where;
	}

	public HQLCriteria build() {
		HQLCriteria crit = getWhere().buildCriteria();
		return crit;
	}

	@Override
	protected And<HQLCriteria> buildAnd(ConditionType type,
			ICondition<HQLCriteria>... conditions) {
		return new AndImpl(type, conditions);
	}

	@Override
	protected Or<HQLCriteria> buildOr(ConditionType type,
			ICondition<HQLCriteria>... conditions) {
		return new OrImpl(type, conditions);
	}

	@Override
	protected Like<HQLCriteria> buildLike(ConditionType type, String value) {
		return new LikeImpl(type, value);
	}

	@Override
	protected In<HQLCriteria> buildIn(ConditionType type,
			ICondition<HQLCriteria> condition1) {
		return new InImpl(type, condition1);
	}
}
